# +--------------------------
# | User: zq                -
# | Version: python3.7      -
# | Time: 2020-03-17 09:57                
# +--------------------------
import time
from selenium import webdriver
from selenium.webdriver import ActionChains  # 鼠标移动到一个元素上
from PIL import Image
from io import BytesIO

# 1 鼠标移动到正确的元素上,显示出没有缺口的图片并下载
# 2 点击元素显示出有缺口的图片并下载
# 3 对比两张图片找到缺口的移动像素
# 4 拖动元素


url = "https://passport.bilibili.com/login"

brower = webdriver.Chrome(
    executable_path="/Users/zhangqiang/Desktop/05-python/03-spider-learn/spider/csdn_spider/chromedriver")


# 截取图片
def crop_image(image_file_name):
    # 截图验证码图片
    # 定位某个元素在浏览器中的位置
    time.sleep(2)
    # img = brower.find_element_by_xpath("//div[@class='geetest_slicebg geetest_absolute']")
    img = brower.find_element_by_xpath("//div[@class='geetest_window']")
    location = img.location
    print("图片的位置", location)
    size = img.size

    top, buttom, left, right = location["y"], location['y'] + size['height'], location['x'], location['x'] + size[
        'width']
    print("验证码位置", left, top, right, buttom)

    screenshot = brower.get_screenshot_as_png()  # 截图成png
    screenshot = Image.open(BytesIO(screenshot))
    captcha = screenshot.crop((int(left), int(top), int(right), int(buttom)))
    captcha.save(image_file_name)
    return captcha


def login():
    username = "454168610@qq.com"
    password = "zl4921272"

    brower.get(url)
    brower.maximize_window()  # 窗口最大化

    # 找到用户名和密码的节点
    username_ele = brower.find_element_by_xpath("//input[@id='login-username']")
    password_ele = brower.find_element_by_xpath("//input[@id='login-passwd']")

    # 写入账号密码
    username_ele.send_keys(username)
    password_ele.send_keys(password)

    # 找到提交节点,点击提交,之后显示滑动验证码
    submit_ele = brower.find_element_by_xpath("//a[@class='btn btn-login']")
    submit_ele.click()

    time.sleep(2)

    # 1 鼠标移动到正确的元素上,显示出没有缺口的图片并下载
    slider = brower.find_element_by_xpath("//div[@class='geetest_slider_button']")
    ActionChains(brower).move_to_element(slider).perform()  # 将鼠标移动到元素上

    # 如何截取图片
    crop_image("captcha1.png")

    time.sleep(1)

    # 获取缺口图片
    ActionChains(brower).click_and_hold(slider).perform()  # 点中元素一直不松左键
    crop_image("captcha2.png")

    # 获取缺口图片的位置


if __name__ == "__main__":
    login()
